<?php

class Test extends Controller {


	function index()
	{
		return;
		// Ставит значения is_real, is_ng, is_ref, is_des, summ_ref для операций покупки
		$this->db->query('delete from '.$this->db->dbprefix."operation where (type = 'buy' and parent_id > 0) or type in ('ref', 'ng', 'l*', 'l**', 'l***', 'l****', 'l*****', 'l*****')");
		$this->db->query("update ".$this->db->dbprefix."operation set is_real = 0, is_ng = 0, is_ref = 0, is_des = 0, summ_ref = 0");
		$opers = $this->MOper->getList(array('sort' => 'date asc,bonus asc'));
		foreach($opers as $o)
		{
			if($o['type'] == 'buy')
			{
				$save = array();
				$save['is_real'] = $o['bonus'] ? 0 : 1;
				$save['is_ng'] = ($o['date'] < '2012-01-17' && $o['date'] > '2011-12-11') || $o['date'] >= '2012-01-18' ? 1 : 0;
				$save['is_ref'] = $save['is_real'];
				$save['is_des'] = $save['is_real'];
				$this->MOper->save($save, $o['id']);
			}
			if($o['type'] == 'sell')
			{
				$save = array();
				$save['is_real'] = $o['bonus'] ? 0 : 1;
				$this->MOper->save($save, $o['id']);
			}
		}
		$saved = array();
		$opers = $this->MOper->getList(array('is_real' => 1, 'type' => 'buy', 'sort' => 'id asc'));
		foreach($opers as $o)
		{
			if(@$saved[$o['user_id']][$o['date']]) continue;
			$opers2 = $this->MOper->getList(array('is_real' => 1, 'type' => 'buy', 'date' => $o['date'], 'user_id' => $o['user_id']));
			$summ = 0;
			foreach($opers2 as $o2)
			{
				$summ += $o2['summ'];
			}
			$save = array('summ_ref' => $summ);
			$this->MOper->save($save, $o['id']);
			$saved[$o['user_id']][$o['date']] = true;
		}
		redirect('test/t2/');
	}


	function t2($id = 0)
	{
		return;
		$this->load->library('Operation');
		$opers = $this->MOper->getList(array('is_real' => 1, 'type' => 'buy', 'sort' => 'id asc', 'id>' => $id, 'count' => 1));
		$new_id = $id;
		foreach($opers as $o)
		{
			$new_id = $o['id'];
			$this->operation->addNG($o);
			$this->operation->addRef($o);
			$this->operation->addDes($o);
		}
		if($new_id <= $id) return;
		?>
		<?=$id?>
<script language="javascript">

self.location.href= '<?=base_url()?>test/t2/<?=$new_id?>';

</script>
		<?
	}

	function t4()
	{
		return;
		$opers = $this->MOper->getList(array('type' => array('modify.sell', 'modify.buy'), 'sort' => 'id asc'));
		foreach($opers as $o)
		{
			if($o['type'] == 'modify.buy')
			{
				continue;
			}
			$o_sell = $o;
			$o_buy = $opers[$o['id'] + 1];

			$kurs_sale = $this->MKurs->getKurs($o_sell['date'], $o_sell['percent'], 'sell');
			$summ_sale = round($o_sell['mavro'] * $kurs_sale, 4);
			$save_sell = array(
				'summ' => $summ_sale,
				'kurs' => $kurs_sale,
			);
//			$this->MOper->save($save_sell, $o_sale['id']);

			$save_buy = array(
				'summ' => $save_sell['summ'],
			);
			$save_buy['mavro'] = getMavro($save_buy['summ'], $o_buy['kurs']);
			if($o_buy['valuta'] != $o_buy['mavro_valuta'])
			{
				$save_buy['mavro'] *= $this->MKurs->getExchange($o_buy['date'], $o_buy['valuta'], $o_buy['mavro_valuta']);
			}
			$save_buy['mavro'] = round($save_buy['mavro'], 4);
//			$this->MOper->save($save_buy, $o_buy['id']);
		}
	}

	function t5()
	{
		return;
		$rows = $this->db->get_where('operation', 'valuta != mavro_valuta')->result_array();
		foreach($rows as $row)
		{
			$kurs_valuta = $this->MKurs->getExchange($row['date'], $row['valuta'], $row['mavro_valuta']);
			$save = array('kurs_valuta' => round($kurs_valuta, 4));
			$this->MOper->save($save, $row['id']);
		}
	}

	function t6()
	{
		return;
		$opers = $this->MOper->getList(array('type' => array('modify.sell', 'modify.buy', 'sell'), 'sort' => 'id asc'));
		foreach($opers as $o)
		{
			if($o['type'] == 'modify.buy')
			{
				continue;
			}
			$o_sell = $o;
			$summ_sale = $o_sell['mavro'] * $o['kurs'];
			if($o_sell['valuta'] != $o_sell['mavro_valuta'])
			{
				$summ_sale *= $this->MKurs->getExchange($o_sell['date'], $o_sell['mavro_valuta'], $o_sell['valuta']);
			}
			$save_sell = array(
				'summ' => round($summ_sale, 4),
			);
			$this->MOper->save($save_sell, $o_sale['id']);

			if($o['type'] == 'modify.sell')
			{
				$o_buy = @$opers[$o['id'] + 1];
				if(@$o_buy['id'])
				{
					$save_buy = array(
						'summ' => $save_sell['summ'],
					);
					$save_buy['mavro'] = getMavro($save_buy['summ'], $o_buy['kurs']);
					if($o_buy['valuta'] != $o_buy['mavro_valuta'])
					{
						$save_buy['mavro'] *= $this->MKurs->getExchange($o_buy['date'], $o_buy['valuta'], $o_buy['mavro_valuta']);
					}
					$save_buy['mavro'] = round($save_buy['mavro'], 4);
					$this->MOper->save($save_buy, $o_buy['id']);
				}
			}
		}
	}

	function t7()
	{
		return;
		$oper = $this->MOper->get(34236);
		$children = $this->operation->getAllChildren($oper);
		echo "<pre>".print_r($children ,true)."</pre>";
	}

	function t8()
	{
		return;
		$text = file_get_contents('http://sergey-mavrodi.com/kurs.php');
		$text = substr($text, strpos($text, "</table>"));
		$text = substr($text, strpos($text, "<tr align=\"center\">"));
		$text = str_replace("\t", "", $text);
		$text = str_replace("<a name='current_day'></a>", "", $text);
		$text = str_replace(' bgcolor="#FFCC99"', "", $text);
		$text = str_replace(' bgcolor="#FFFFCC"', "", $text);
		$text = str_replace(' bgcolor="#EEEEEE"', "", $text);
		$text = str_replace(' bgcolor="#FFA602"', "", $text);
		$text = str_replace(' style="width:96px;"', "", $text);
		$text = str_replace(' style="width:41px;"', "", $text);
		$text = str_replace(' style="width:51px;"', "", $text);
		$text = str_replace(' style="width:61px;"', "", $text);
		$text = str_replace(' style="width:60px;"', "", $text);
		$text = str_replace(' style="width:69px;"', "", $text);
		$text = str_replace(' style="width:42px;"', "", $text);
		$text = str_replace('<b>', "", $text);
		$text = str_replace('</b>', "", $text);
		$text = str_replace('<td>', "", $text);
		$text = str_replace('</td>', "", $text);
		$text = str_replace('</tr>', "", $text);
		$text = str_replace('<br />', "", $text);
		$text = str_replace(iconv('windows-1251', 'utf-8', '(Чт.)'), "", $text);
		$text = str_replace(iconv('windows-1251', 'utf-8', '(Вт.)'), "", $text);
		$text = str_replace(iconv('windows-1251', 'utf-8', '<span style=\'font-size:14px\'>ном.</span>'), "", $text);
		$arr = explode("\n", $text);
		$begin = true;
		$percent = 20;
		foreach($arr as $row)
		{
			$row = trim($row);
			if($row == '') continue;
			if(substr($row, 0, 8) == '</tbody>') continue;
			if(substr($row, 0, 3) == '<tr')
			{
				$begin = true;
				continue;
			}
			if($begin)
			{
				list($d, $m, $y) = explode(".", $row);
				$date = dateToDb($y."-".$m.'-'.$d);
				$begin = false;
				$percent = 20;
				continue;
			}
			list($buy, $sell) = explode("<hr>", $row);
			$buy = trim(str_replace(",", ".", $buy));
			$sell = trim(str_replace(",", ".", $sell));
			$arr = array(
				'date' => $date,
				'percent' => $percent,
				'buy' => $buy,
				'sell' => $sell
			);
			$percent += 10;
			if($percent == 70) 
			{
				$percent = 45;
			}
			$this->MKurs->updateKurs($arr);
		}
	}

	function t9()
	{
		return
		// Пока отказались от использования этой функции

		// !!! Прежде, чем выполнить, надо запустить по всем пользователям пересчёт бонусов

		// 1. Убирает привязку у всех операций.
		// 2. Делает привязку бонусов сотника и выше к бонусам десятника

		$opers_des = $this->MOper->getList(array('type' => 'l*'));
		foreach($opers_des as $o)
		{
			$this->db->query("update ".$this->db->dbprefix."operation set parent_id = ".$o['id']." where parent_id = ".$o['parent_id']." and type in ('l**', 'l***', 'l****', 'l*****', 'l******')");
		}
		$this->db->query("update ".$this->db->dbprefix."operation set parent_id = 0 where type not in ('l**', 'l***', 'l****', 'l*****', 'l******')");
	}

	function t10()
	{
		return;
		// Выставляет значение num для всех операций
		$this->db->order_by('date', 'asc');
		$this->db->order_by('id', 'asc');
		$res = $this->db->get('operation');
		$rows = $res->result('array');
		$num = 1;
		foreach($rows as $row)
		{
			$this->db->update('operation', array('num' => $num), array('id' => $row['id']));
			$num++;
		}
	}

	function t11()
	{
		return;
		// Ставит правильный остаток по операциям покупки
		global $TYPE_OPER;
		$types = $TYPE_OPER;
		unset($types['sell']);
		unset($types['modify.sell']);
		$types = array_keys($types);
		foreach($opers as $o)
		{
			if($o['mavro'] != $o['ostatok']) continue;
			$children = $this->MOper->getList(array('parent_id' => $o['id']));
			$ostatok = $o['ostatok'];
			foreach($children as $ch)
			{
				if(!isBuy($ch))
				{
					$ostatok -= $ch['mavro'];
				}
			}
			if($ostatok != $o['ostatok'])
			{
				$save = array();
				$save['ostatok'] = max($ostatok, 0);
				$this->MOper->save($save, $o['id']);
			}
		}
	}

	function t12()
	{
		return;
		$opers = $this->MOper->getList(array('ostatok>' => 0, 'sort' => 'id asc', 'count' => 3000, 'offset' => 9000));
		echo count($opers);
		foreach($opers as $oper)
		{
			$save = array('ostatok' => round($oper['ostatok'], 4));
			$this->MOper->save($save, $oper['id']);
		}
	}

	function t13()
	{
		// Проставляет в операциях начисления бонуса за регистрацию колонку depo
		$users = $this->MUser->getList();
		$opers = $this->MOper->getList(array('sort' => 'id asc', 'type' => 'reg', 'percent>' => 20));
		foreach($opers as $oper)
		{
			$user = @$users[$oper['user_id']];
			$user_is_lgota = $this->MUser->isLgota($user, $oper['date'], $oper['type']);
			$depo = getDepoMonth($user_is_lgota, $oper['percent']);
			$save = array('depo' => $depo);
			$this->MOper->save($save, $oper['id']);
		}
	}

	function t14($parent_id = 0, $parent_hi = '')
	{
		// Создание hi для каждого пользователя
		$users = $this->MUser->getList(array('parent_id' => $parent_id, 'sort' => 'level desc,id asc'));
		$num = 1;
		foreach($users as $u)
		{
			$hi = $parent_hi.($parent_hi ? "." : '').createHi($num);
			$this->MUser->save(array('hi' => $hi), $u['id']);
			$this->t14($u['id'], $hi);
			$num++;
		}
	}

	function t15()
	{
		return;
		mysql_query("
CREATE FUNCTION get_last_part_hi(hi VARCHAR(255))
  RETURNS int(11)
  DETERMINISTIC
  NO SQL
BEGIN
  DECLARE dot_pos             INT(10);

  SET dot_pos = length(hi) - locate('.', reverse(hi)) + 1;
  RETURN if(dot_pos > 0 AND dot_pos < length(hi), substring(hi, dot_pos + 1), hi);

END
		");

		mysql_query("
CREATE FUNCTION get_last_user_hi(parent_hi VARCHAR(255))
  RETURNS varchar(255) CHARSET utf8
  DETERMINISTIC
BEGIN
  declare last_hi varchar(255);
  DECLARE parent_part VARCHAR(255);

SELECT hi
FROM
  `user`
WHERE
  hi LIKE concat(parent_hi, '.%')
  AND hi_level(hi) = hi_level(parent_hi) + 1
ORDER BY
  hi DESC
LIMIT
  1
INTO
  last_hi;

  SET parent_part = ifnull(parent_hi, '');
  SET parent_part = if(parent_part = '', '', concat(parent_part, '.'));
  SET last_hi = ifnull(last_hi, concat(parent_part, '00'));

RETURN last_hi;
END
		");
		mysql_query("
CREATE FUNCTION get_next_hi(hi VARCHAR(255))
  RETURNS varchar(255) CHARSET utf8
  DETERMINISTIC
  NO SQL
BEGIN
  DECLARE last_part_hi   VARCHAR(255);
  DECLARE parent_part_hi VARCHAR(255);
  DECLARE dot_pos        INT(10);
  DECLARE last_part_hi_number INT(10);

  SET dot_pos = length(hi) - locate('.', reverse(hi)) + 1;
  SET last_part_hi = if(dot_pos > 0 AND dot_pos < length(hi), substring(hi, dot_pos + 1), hi);
  SET parent_part_hi = if(dot_pos > 0 AND dot_pos < length(hi), substring(hi, 1, dot_pos), '');
  SET last_part_hi_number = if(last_part_hi = '', 0, cast(substring(last_part_hi, 2) AS UNSIGNED)) + 1;

  RETURN concat(parent_part_hi, cast(length(cast(last_part_hi_number as char)) - 1 as char), cast(last_part_hi_number as char));
END
		");
		mysql_query("
CREATE FUNCTION hi_level(hi VARCHAR(255))
  RETURNS int(11)
  DETERMINISTIC
  SQL SECURITY INVOKER
  NO SQL
BEGIN
RETURN if(hi = '', 0, length(hi) - length(replace(hi, '.', '')) + 1);
END
		");
		mysql_query("
CREATE FUNCTION parent_hi(hi VARCHAR(255))
  RETURNS varchar(255) CHARSET utf8
  DETERMINISTIC
  NO SQL
BEGIN
  DECLARE dot_pos             INT(10);

  SET dot_pos = length(hi) - locate('.', reverse(hi)) + 1;
  RETURN if(dot_pos > 0 AND dot_pos < length(hi), substring(hi, 1, dot_pos - 1), '');

END
		");
	}

	function t16()
	{
		return;
		mysql_query('ALTER TABLE `operation` ADD `frozen_date` DATE AFTER `ostatok`');
		mysql_query('ALTER TABLE `operation` ADD `frozen_summ` DOUBLE AFTER `frozen_date`');
	}


	function t17($index = 0)
	{
		return;
		// Выставляет дату разморозки для разных операций

		$types = array('reg', 'week', 'buy', 'ng', 'ref', 'l*', "l**", "l***", "l****", "l*****", "l******", 'modify.buy');

		if(isset($types[$index]))
		{
			$type = $types[$index];

			$opers = $this->MOper->getList(array('type' => $type, 'sort' => 'id asc'));
			foreach($opers as $oper)
			{
				operUpdateFrozen($oper);
			}
			?>
			<script language="javascript">
			self.location.href = "<?=base_url()?>test/t17/<?=$index+1?>";
			</script>
			<?php
		}
	}

	function t18($min_id = 0)
	{
		return;
		// у всех операций переоформления-покупка ставит parent_id = операции переоформления-продажа
		$oper = $this->MOper->getFirstRow(array('type' => 'modify.buy', 'id>' => $min_id, 'sort' => 'id asc'));
		if(!@$oper['id'])
		{
			?>
			<script language="javascript">
			self.location.href = '<?=base_url()?>test/t17/11/';
			</script>
			<?
			return;
		}
		$parent_oper = $this->MOper->get($oper['parent_id']);
		if(@$parent_oper['type'] != 'modify.sell')
		{
			$oper2 = $this->MOper->getFirstRow(array('type' => 'modify.sell', 'parent_id' => $oper['parent_id'], 'id<' => $oper['id'], 'sort' => 'id desc'));
			if(@$oper2['id'])
			{
				$save = array('parent_id' => $oper2['id']);
				$this->MOper->save($save, $oper['id']);
			}
		}
		operUpdateFrozen($oper);
		?>
		<script language="javascript">
		self.location.href = '<?=base_url()?>test/t18/<?=$oper['id']?>';
		</script>
		<?
	}

	function t19()
	{
		return;
		// Начисление всем операциям покупки дополнительных патриотических и арестанстских бонусов
		$this->load->library('Operation');
		$opers = $this->MOper->getList(array('type' => 'buy', 'bonus' => 0, 'date>=' => PATRIOT_BONUS_BEGIN, 'date<=' => AREST_BONUS_END));
		foreach($opers as $oper)
		{
			if($oper['_tmp_add_ng'])
			{
				if($oper['date'] >= PATRIOT_BONUS_BEGIN && $oper['date'] <= PATRIOT_BONUS_END)
				{
					$this->operation->addPatriotBonus($oper, $oper['_tmp_ng_summ']);
				}
				elseif($oper['date'] >= AREST_BONUS_BEGIN && $oper['date'] <= AREST_BONUS_END)
				{
					if($this->MOper->getCount(array('type' => 'buy', 'bonus' => 0, 'user_id' => $oper['user_id'], 'date>=' => PATRIOT_BONUS_BEGIN, 'date<=' => PATRIOT_BONUS_END)))
					{
						$this->operation->addPatriotBonus($oper, $oper['_tmp_ng_summ']);
					}
					else
					{
						$this->operation->addArestBonus($oper, $oper['_tmp_ng_summ']);
					}
				}
			}
		}
	}

	function t20()
	{
		return;
		$this->db->query('ALTER TABLE `operation` CHANGE `dop` `dop` VARCHAR( 1000 )');
		$this->db->query('UPDATE operation set hranen = "победный бонус 15%" WHERE type = "arest"');
	}

	function t21()
	{
		return;
		$this->db->query('alter table user add column `update_password` tinyint (1) default 0');
		?>
		<script language="javascript">
		
		self.location.href = '<?=base_url()?>test/t22/'
		
		</script>
		<?
	}

	function t22($min_id = 0)
	{
		return;
		// установка для всех пользователей пароля в формате md5
		$users = $this->MUser->getList(array('id>' => $min_id, 'password<>' => '', 'update_password' => 0, 'sort' => 'id asc', 'count' => 10));
		$max_id = $min_id;
		foreach($users as $user)
		{
			$pass = md5($user['password']);
			$arr = array('password' => $pass, 'update_password' => 1);
			$this->MUser->save($arr, $user['id']);
			$max_id = max($max_id, $user['id']);
		}
		if($max_id == $min_id)
		{
			return;
		}
		?>
		<script language="javascript">
		
		self.location.href = '<?=base_url()?>test/t22/<?=$max_id?>'
		
		</script>
		<?
	}

	function t23()
	{
			$sql = "select u1.id, u1.hi, u1.fio from 
					user u1,
					user u2
				where
					u1.id = u2.parent_id
					and u2.hi not like concat(u1.hi, '.%')
				group by u1.hi;
				";
			$res2 = mysql_query($sql);
			while($row = mysql_fetch_assoc($res2))
			{
				echo "<pre>".print_r($row, true)."</pre>";
			}
		echo mysql_error();
		echo 'ok';
	}




}


